package ute.mvc.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ute.mvc.model.MyClass;
import ute.mvc.model.OpenCourse_Subject;
import ute.mvc.model.Question;
import ute.mvc.model.TestAndQuizz;
import ute.mvc.model.User;

@Repository("testAndQuizzDAO")
public class TestAndQuizzDAOImpl implements TestAndQuizzDAO {
	@Autowired
	SessionFactory sessionFactory;

	public void addTestAndQuizz(TestAndQuizz testAndQuizz) {
		sessionFactory.getCurrentSession().save(testAndQuizz);
	}

	public void updateTestAndQuizz(TestAndQuizz testAndQuizz) {
		sessionFactory.getCurrentSession().merge(testAndQuizz);
	}

	public void deleteTestAndQuizz(TestAndQuizz testAndQuizz) {
		sessionFactory.getCurrentSession().delete(testAndQuizz);
	}

	public TestAndQuizz getTestAndQuizz(String id) {
		// TODO Auto-generated method stub
		return (TestAndQuizz) sessionFactory.getCurrentSession().get(
				TestAndQuizz.class, id);
	}

	public String getMaxIdInOpenCourseSubject(OpenCourse_Subject subject) {
		// TODO Auto-generated method stub
		Criteria criteria = sessionFactory.getCurrentSession()
				.createCriteria(TestAndQuizz.class)
				.add(Restrictions.eq("openCourse_Subject", subject))
				.setProjection(Projections.max("testAndQuizzID"));
		String maxId = (String) criteria.uniqueResult();
		return maxId;
	}

	@SuppressWarnings("unchecked")
	public List<TestAndQuizz> getTestBySubject(OpenCourse_Subject subject,
			User user) {
		// TODO Auto-generated method stub
		List<TestAndQuizz> list = sessionFactory.getCurrentSession()
				.createCriteria(TestAndQuizz.class)
				.add(Restrictions.eq("openCourse_Subject", subject))
				.add(Restrictions.eq("lecturer", user)).list();
		return list;
	}

	@SuppressWarnings("unchecked")
	public List<MyClass> getClassByTestId(String testId) {
		List<MyClass> list = sessionFactory.getCurrentSession()
				.createCriteria(MyClass.class).createCriteria("listTest")
				.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
				.add(Restrictions.eq("testAndQuizzID", testId)).list();
		return list;
	}

}
